﻿using System.Collections.Generic;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System;
using System.Xml.Serialization;

namespace DotNet.Common
{
	/// <summary>
	/// 最近的文件列表类
	/// </summary>
	public class RecentFileMenuList
	{
		private int m_MaxCount;
		private ToolStripMenuItem[] m_RecentMenus;
		List<string> m_RecentFilepath;

		/// <summary>
		/// 文件打开，注意：应实现添加列表项功能
		/// </summary>
		public event FileInvoker OnFileOpen;	

		/// <summary>
		/// 构造函数
		/// </summary>
		public RecentFileMenuList() : this(10)
		{
		}

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="count">菜单数目</param>
		public RecentFileMenuList(int count)
		{
			MaxCount = count;
			m_RecentFilepath = new List<string>();
		}

		[XmlArray("Items"), XmlArrayItem("Item")]
		public List<string> FilePathList
		{
			get
			{
				return m_RecentFilepath;
			}
			set
			{
			}
		}

		/// <summary>
		/// 设置菜单数目
		/// </summary>
		private int MaxCount
		{
			set 
			{
				m_MaxCount = value;
				m_RecentMenus = new ToolStripMenuItem[m_MaxCount];
				for (int i = 0; i < m_MaxCount; i++)
				{
					m_RecentMenus[i] = new ToolStripMenuItem();
					m_RecentMenus[i].Tag = i;
					m_RecentMenus[i].Visible = false;
					m_RecentMenus[i].Click += RecentFilesList_Click;
				}
			}
		}
		
		/// <summary>
		/// 路径缩写
		/// </summary>
		public string[] ShortFilePathList
		{
			get
			{
				int index = 0;
				string[] shortFilepaths = new string[m_RecentFilepath.Count];
				foreach (string filepath in m_RecentFilepath)
				{
					shortFilepaths[index++] = GetShortFilepath(filepath);
				}

				return shortFilepaths;
			}
		}

		public int Count
		{
			get
			{
				return m_RecentFilepath.Count;
			}
		}

		public string this[int index]
		{
			get
			{
				return m_RecentFilepath[index];
			}
		}

		/// <summary>
		/// 加载最近的文件菜单
		/// </summary>
		/// <param name="recentRootMenu">菜单控件</param>
		/// <param name="fileOpenFunc">打开文件委托</param>
		public void Load(ToolStripMenuItem recentRootMenu,FileInvoker fileOpenFunc)
		{
			if (recentRootMenu.HasDropDownItems)
				throw new Exception("RecentRootMenu不应该含有子菜单。");
			recentRootMenu.DropDownItems.AddRange(m_RecentMenus);

			OnFileOpen += fileOpenFunc;
			Update();
		}

		/// <summary>
		/// 删除项
		/// </summary>
		/// <param name="index">编号</param>
		private void Delete(int index)
		{
			if (index < this.Count)
			{
				m_RecentFilepath.RemoveAt(index);
				Update();
			}
		}

		/// <summary>
		/// 删除项
		/// </summary>
		/// <param name="filepath">路径</param>
		private void Delete(string filepath)
		{
			if (m_RecentFilepath.Remove(filepath))
			{
				Update();
			}
		}

		/// <summary>
		/// 添加项
		/// </summary>
		/// <param name="filepath">路径</param>
		public void Add(string filepath)
		{
			int index = m_RecentFilepath.IndexOf(filepath);
			int count = m_RecentFilepath.Count;

			if (index == 0)
			{
				return;
			}
			else if (index > 0)
			{
				m_RecentFilepath.RemoveAt(index);
			}
			else
			{
				if (count == m_MaxCount)
				{
					m_RecentFilepath.RemoveAt(count - 1);
				}
			}

			m_RecentFilepath.Insert(0, filepath);

			Update();
		}

		/// <summary>
		/// 打开文件
		/// </summary>
		/// <param name="index">编号</param>
		/// <returns></returns>
		public bool OpenFile(int index)
		{
			if (index < 0 || index >= m_RecentFilepath.Count)
				return false;

			string filepath = m_RecentFilepath[index];

			return OpenFile(filepath);
		}

		/// <summary>
		/// 打开文件
		/// </summary>
		/// <param name="filepath">路径</param>
		/// <returns></returns>
		public bool OpenFile(string filepath)
		{
			if (OnFileOpen != null)
			{
				if (OnFileOpen(filepath))
				{
					return true;
				}
				else
				{
					this.Delete(filepath);
					return false;
				}
			}
			else
			{
				return true;
			}
		}

		/// <summary>
		/// 更新子菜单
		/// </summary>
		private void Update()
		{
			if (m_RecentMenus != null)
			{
				string[] path = this.ShortFilePathList;
				int pathCount = path.Length;
				string formatStr;
				for (int index = 0; index < m_RecentMenus.Length; index++)
				{
					if (index < pathCount)
					{
						if (index == 0)
						{
							formatStr = "{0} {1}(&{0})";
						}
						else if (index == 9)
						{
							formatStr = "{0} {1}(1&{0})";
						}
						else
						{
							formatStr = "{0} {1}({0})";
						}
						m_RecentMenus[index].Text = string.Format(formatStr, index + 1, path[index]);
						m_RecentMenus[index].Visible = true;
					}
					else
					{
						m_RecentMenus[index].Visible = false;
					}
				}
			}
		}

		/// <summary>
		/// 点击子菜单
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void RecentFilesList_Click(object sender, System.EventArgs e)
		{
			int index = (int)((sender as ToolStripMenuItem).Tag);
			this.OpenFile(index);
		}

		/// <summary>
		/// 获取短路径
		/// </summary>
		/// <param name="filepath"></param>
		/// <returns></returns>
		private static string GetShortFilepath(string filepath)
		{
			if (string.IsNullOrEmpty(filepath))
				return filepath;

			if (filepath.Length > 40)
			{
				return Regex.Replace(filepath, @"(?<=^\w:\\.+\\).+(?=\\.+\\.+)", "...");
			}
			else
			{
				return filepath;
			}
		}
	}
}
